/**
 * 常用方法封装 请求，文件上传等
 * @author echo. 
 **/
import wx from 'jweixin-module'
const tui = {
	//接口地址
	interfaceUrl: function() {
		var configInfo = uni.getStorageSync('configInfo')
		// return 'https://kuaiduomiadmin.zzcyx1688.cn//overall/' //快多来
		// return 'https://qclargeadmin.zzcyx1688.cn/overall/' //清春
		// return 'https://quanmgadmin.zzcyx1688.cn/overall/' //全民优选 
		// return 'https://laobaixing.zzcyx1688.cn/overall/' //老百姓
		// return 'https://liulaosadmin.zzcyx1688.cn/overall/' //刘老送
		// return 'https://fangqizhibo.zzcyx1688.cn/overall/' //方琦
		// return 'https://huanglegomanagera.zzcyx1688.cn/overall/' //欢乐GO一号店
		// return 'https://xlzhenxuan.zzcyx1688.cn/overall/' //流进岁月
		// return 'https://zhennuoadmin.zzcyx1688.cn/overall/' //真诺优选
		// return 'https://qclargeadmin.zzcyx1688.cn/overall/'清春总控
		// return 'https://nkzbmanager.zzcyx1688.cn/overall/' //五福甄选
		// return 'https://liuzpointm.zzcyx1688.cn/overall/' //五福甄选
		// return 'https://liujincxadmin.zzcyx1688.cn/overall/' //流金岁月
		// return 'https://gmyouxuanmanager.zzcyx1688.cn/overall/' //国民一
		// return 'https://gmpointm.zzcyx1688.cn/overall/' //国民二
		// return 'https://czmadmin.zzcyx1688.cn/overall/' //创之梦一号店
		// return 'https://gongxiaomanager.zzcyx1688.cn/overall/' //供销惠民
		// return 'https://gong-qingchunadmin.zzcyx1688.cn/overall/' //清春有约
		// return 'https://gongxiaolifexuan.zzcyx1688.cn/overall/' //供销优选
		// return 'https://gongxiaolife.zzcyx1688.cn/overall/' //供销优生活
		// return 'https://xlzhenxuan.zzcyx1688.cn/overall/' //供销优生活
		// return 'https://qingchunadmin.zzcyx1688.cn/overall/' //蜜蜂回家
		// return 'https://czmmanager.zzcyx1688.cn/overall/' //康耀清春
		// return 'https://mctglamad.zzcyx1688.net/overall/' //必行天下
		// return 'https://'+ window.location.host+"/overall/" //供销惠生活
		return configInfo.item.admin_url + 'overall/' //供销甄选
		// return 'https://chuntotal.chen1413.com/overall/'
		
		
		
	},
	faceUrl: function() {
		return 'https://'+window.location.host+window.location.pathname //清春乐购
		// return 'http://zblive.wyc168.com/' //测式
		// return 'http://zblives.wyc168.com/' //第一
	},
	appid:function(){
		return 'wx166a5f1762a0e6e8'
	},
	toast: function(text, duration, success) {
		uni.showToast({
			title: text ,
			icon: success ? 'success' : 'none',
			duration: duration || 2000
		})
	},
	modal: function(title, content, showCancel, callback, confirmColor, confirmText) {
		uni.showModal({
			title: '提示',
			content: content,
			showCancel: showCancel,
			cancelColor: "#555",
			confirmColor: confirmColor || "#5677fc",
			confirmText: confirmText || "确定",
			success(res) {
				if (res.confirm) {
					callback && callback(true)
				} else {
					callback && callback(false)
				}
			}
		})
	},
	isAndroid: function() {
		const res = uni.getSystemInfoSync();
		return res.platform.toLocaleLowerCase() == "android"
	},
	constNum: function() {
		let time = 0;
		// #ifdef APP-PLUS
		time = this.isAndroid() ? 300 : 0;
		// #endif
		return time
	},
	delayed: null,
	/**
	 * 请求数据处理
	 * @param string url 请求地址
	 * @param string method 请求方式
	 *  GET or POST
	 * @param {*} postData 请求参数
	 * @param bool isDelay 是否延迟显示loading
	 * @param bool isForm 数据格式
	 *  true: 'application/x-www-form-urlencoded'
	 *  false:'application/json'
	 * @param bool hideLoading 是否隐藏loading
	 *  true: 隐藏
	 *  false:显示
	 */
	request: function(url, method, postData, isDelay, isForm, hideLoading) {
		//接口请求
		let loadding = false;
		tui.delayed && uni.hideLoading();
		clearTimeout(tui.delayed);
		tui.delayed = null;
		
		if (!hideLoading) {
			tui.delayed = setTimeout(() => {
				uni.showLoading({
					mask: true,
					title: '请稍候...',
					success(res) {
						loadding = true
					}
				})
			}, isDelay ? 1000 : 0)
		}
		// uni.setStorageSync("d_token", '8e099eb666f9aed836411bc147bfa825')
		// uni.setStorageSync("d_token", '01931e675a763db0b619c337052f6d7e')
		postData.equipment_type = 2
		return new Promise((resolve, reject) => {
			uni.request({
				url: tui.interfaceUrl() + url,
				data: postData,
				header: {
					// 'content-Type': 'application/json',
					'content-type':'application/x-www-form-urlencoded',
					'authorization': tui.getToken(),
					// 'equipment-type':2,
				},
				method: method, //'GET','POST'
				dataType: 'json',
				success: (res) => {
					console.log(res)
					clearTimeout(tui.delayed)
					tui.delayed = null;
					if (loadding && !hideLoading) {
						uni.hideLoading()
					}
					if(res.data.code==1){
						resolve(res.data)
					} else if (res.data.code ==401) {
						uni.removeStorage({
						    key: 'd_token',
						    success: function (res) {
						        console.log('success');
						    }
						});
						uni.removeStorage({
						    key: 'refCode',
						    success: function (res) {
						        console.log('success');
						    }
						});
						let local = location.href;
						uni.setStorageSync('d_url', local)
						uni.$emit("isbtn",true)
						// tui.wetLogin()
						tui.toast('登录失效,请重新登录')
						setTimeout(function(){
							uni.redirectTo({
								url: '/pages/login/login'
							})
						},1000)
						return
					}else if (res.data.code==407){
						tui.toast(res.data.info)
						uni.$emit("isbtn",true)
						setTimeout(function(){
							uni.navigateTo({
								url: '/pages/MyOrderList/MyOrderList?type=0'
							})
						},1000)
					}else{
						tui.toast(res.data.info)
						uni.$emit("isbtn",true)
						if(res.data.info=="收款方式不能为空"){
							setTimeout(function(){
								tui.href('/pages/bank/bank_list_1')
							},1000)
						}
					}
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")
					reject(res)
				}
			})
		})
	},
	/**
	 * 上传文件
	 * @param string url 请求地址
	 * @param string src 文件路径
	 */
	uploadFile: function(url, src) {
		let that = this
		uni.showLoading({
			title: '请稍候...'
		})
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: tui.interfaceUrl() + url,
				filePath: src,
				name: 'file',
				header: {
					'authorization':  tui.getToken(),
				},
				success: function(res) {
					uni.hideLoading()
					let d = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}")
					console.log(d)
					let fileObj = d;
					resolve(fileObj)
				},
				fail: function(res) {
					reject(res)
					that.toast(res.msg);
				}
			})
		})
	},
	getRoomSwitch(e){
		let that = this
		return new Promise((resolve, reject) => {
			uni.request({
				url:'https://live-common.weibaozb.com/api/config/shopScan',
				data:{identification:e,url:tui.faceUrl()},	
				header: {
					'content-type':'application/x-www-form-urlencoded',
					'authorization': tui.getToken(),
				},
				method: 'POST', //'GET','POST'
				dataType: 'json',
				success: (res) => {
					console.log(res)
					if(res.data.code==1){
						uni.setStorageSync('configInfo', res.data.data)
						resolve(res.data)
					}
				},
				fail: (res) => {
					clearTimeout(tui.delayed)
					tui.delayed = null;
					tui.toast("网络不给力，请稍后再试~")	
				}
			})	
		})
		
	},
	tuiJsonp: function(url, callback, callbackname) {
		// #ifdef H5
		window[callbackname] = callback;
		let tuiScript = document.createElement("script");
		tuiScript.src = url;
		tuiScript.type = "text/javascript";
		document.head.appendChild(tuiScript);
		document.head.removeChild(tuiScript);
		// #endif
	},
	//设置用户信息
	setUserInfo: function(mobile,token) {
		//uni.setStorageSync("thorui_token", token)
		uni.setStorageSync("thorui_mobile", mobile)
	},
	//获取token
	getToken() {
		return uni.getStorageSync("d_token")
	},
	//判断是否登录
	isLogin: function() {
		return uni.getStorageSync("d_token") ? true : false
	},
	//跳转页面，校验登录状态
	href(url, isVerify) {
		if (isVerify && !tui.isLogin()) {
			uni.navigateTo({
				url: '/pages/common/login/login'
			})
		} else {
			uni.navigateTo({
				url: url
			});
		}
	},
	dianji(fn) {
	    let that = this;
		let is_true = getApp().globalData.is_true
		console.log(is_true)
	    if (is_true) {
	        getApp().globalData.is_true = false;
	        setTimeout(function () {
	            getApp().globalData.is_true = true;
	        }, 5000)
			fn();
	    } else {
	        //如果一直走else分支可能是你没有在页面的data下面挂载onoff:true,不然一直都会走else
	        console.log("请稍后点击")
	    }
	},
	wetLogin(e,d){
		let that = this
		// #ifdef H5
		let urls =tui.faceUrl()+ "#/pages/login/login"
		let url=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=`+tui.appid()+`&redirect_uri=`+encodeURIComponent(urls)+`&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect`;
		window.location.href = url
		// #endif
		// #ifdef MP
		uni.login({
			provider: 'weixin',
			success: (res) => {
				let data = {code: res.code,inviter_code:uni.getStorageSync('refCode'),openid_inviter_code:uni.getStorageSync('share_openid')}
				tui.request("api.wxapp/session", "POST", data, false, false, true).then((res) => {
					console.log(res)
					tui.toast(res.info)
					uni.removeStorage({
					    key: 'refCode',
					    success: function (res) {
					        console.log('success');
					    }
					});
					uni.setStorageSync('d_token', res.data.token)
					uni.setStorageSync('headimg', res.data.headimg)
					uni.setStorageSync('inviter_code', res.data.inviter_code)
					uni.$emit("isLogin",1)
					if(res.data.is_avatar==2){
						console.log(res.data.is_avatar)
						uni.$emit("isShow",res.data.is_avatar)
					}
					if(e==1){
						tui.getList(d)
					}
				}).catch((res) => {
					that.is_btn = false
				})
			},
		});
		// #endif
		
	},
	TongjiLive(e,d){
		let that = this
		console.log(e,d+"qweqweqweqweqe")
		let equipment = ''
		uni.getSystemInfo({
		    success: function (res) {
		        console.log(res);
				equipment = res.system
		    }
		});
		if(d==0){
			return
		}
		return
		tui.request("api.auth.live/lookLive", "POST", {type:e,room_id:d,equipment:equipment}, false, false, true).then((res) => {
			console.log(res)
			if(res.code==1){
				uni.setStorageSync('lookLive', e)
			}
		}).catch((res) => {
			
		})
	},
	getList(e,d){
		let that = this
		tui.request("api.auth.live/liveRoomMtnEwWechat", "POST", {page:1}, false, false, true).then((res) => {
			if(res.code==1){
				if(res.data.list){
					res.data.list.map((item,index)=>{
						if(e==item.id){
							uni.setStorageSync('room_id', item.course_id)
							uni.setStorageSync('zhiboStatus',item)
							if(d==1){
								tui.href('/pages/zhibo/zhibo?zhiboid='+item.id+"&inviter_code="+uni.getStorageSync('inviter_code'))
							}else{
								window.location.href =tui.faceUrl()+'#/pages/zhibo/zhibo?zhiboid='+item.id+"&inviter_code="+uni.getStorageSync('inviter_code')
							}
							
						}
					})
				}else{
					if(d==2){
						window.location.href =tui.faceUrl()+'#/pages/home/home'
					}
				}
			}
		}).catch((res) => {
			
		})
	},
	phoneYin(phone){
		if(phone){
			return  phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
		}
	},
	phoneMore(phone){
		var arr = phone.split(',')
		var data =''
		arr.map((item,index)=>{
			data = data+item.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')+','
		})
		data = data.slice(0, -2)
		if(phone){
			return  data;
		}
	},
	getBindcode(){
		let that = this
		tui.request("api.auth.live/blindInfo", "POST", {}, false, false, true).then((res) => {
			if(res.code==1){
				if(res.data.pid0==0){
					if(res.data.inviter_code_arr.indexOf(uni.getStorageSync('refCode'))!=-1){
						tui.request("api.auth.live/invBlind", "POST", {inviter_code:uni.getStorageSync('refCode')}, false, false, true).then((res) => {
							
						}).catch((res) => {
						
						})
					}
				}
			}
		}).catch((res) => {
		
		})
	},
	setIncrement(val) {
	    let status = false,
	    step = 3.30* val / (1000 / 30),
	    count  = 0,
	    interval = null;
	    interval = setInterval(() => {
	        if(count < val) {
	            count = count + step;
	        } else {
	            status = true
				count = val
	        }
	        if(status) {
	            clearInterval(interval)
	        }
			return count
	    }, 30)
		
	},
	secondsToTime(seconds) {
	  const hours = Math.floor(seconds / 3600);
	  const minutes = Math.floor((seconds % 3600) / 60);
	  const remainingSeconds = seconds % 60;
	  return hours + "时" + minutes + "分" + remainingSeconds + "秒" ;
	},
	wxShare() {
		let that = this
		let res = uni.getStorageSync('configInfo')
		
		wx.config({
		  debug: false, // 是否开启调试模式
		  appId: res.scan.info.appId, // 必填，公众号的唯一标识
		  timestamp: res.scan.info.timestamp, // 必填，生成签名的时间戳
		  nonceStr: res.scan.info.nonceStr, // 必填，生成签名的随机串
		  signature: res.scan.info.signature, // 必填，签名，见附录1
		  jsApiList: res.scan.info.jsApiList
		})
		tui.wxReady()
	},
	wxReady() {
		let url =''
		let res = uni.getStorageSync('configInfo')
		url = tui.faceUrl()+'#/?type='+res.item.identification  //直播间
		console.log(url)
		wx.ready(function() {
			wx.onMenuShareAppMessage({
				title: res.scan.title, // 分享标题  
				desc: res.scan.desc, // 分享描述  
				link: url, // 分享链接  
				imgUrl: res.scan.share_img, // 分享图标
				success: res => {
					// 用户确认分享后执行的回调函数
					console.log(res)
					console.log('分享成功')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},  
				cancel: res => {
					// 用户取消分享后执行的回调函数
					console.log(res)
					console.log('bbbbbbb')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},
				fail: res => {
					console.log(res)
					console.log('cccccc')
				}
			});
			wx.onMenuShareTimeline({
				title: res.scan.title, // 分享标题
				desc: res.scan.desc, // 分享描述  
				link: url, // 分享链接  
				imgUrl: res.scan.share_img, // 分享图标
				success: res => {
					// 用户确认分享后执行的回调函数
					console.log(res)
					console.log('分享成功')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},  
				cancel: res => {
					// 用户取消分享后执行的回调函数
					console.log(res)
					console.log('bbbbbbb')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},
				fail: res => {
					console.log(res)
					console.log('cccccc')
				}
			});
			wx.onMenuShareTimeline({
				title: res.scan.title, // 分享标题
				desc: res.scan.desc, // 分享描述  
				link: url, // 分享链接  
				imgUrl: res.scan.share_img, // 分享图标
				success: res => {
					// 用户确认分享后执行的回调函数
					console.log(res)
					console.log('分享成功')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},  
				cancel: res => {
					// 用户取消分享后执行的回调函数
					console.log(res)
					console.log('bbbbbbb')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},
				fail: res => {
					console.log(res)
					console.log('cccccc')
				}
			});
			wx.onMenuShareAppMessage({
				title: res.scan.title, // 分享标题
				desc: res.scan.desc, // 分享描述  
				link: url, // 分享链接  
				imgUrl: res.scan.share_img, // 分享图标
				success: res => {
					// 用户确认分享后执行的回调函数
					console.log(res)
					console.log('分享成功')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},  
				cancel: res => {
					// 用户取消分享后执行的回调函数
					console.log(res)
					console.log('bbbbbbb')
						uni.removeStorage({
						    key: 'shareUrl',
						    success: function (res) {
						        console.log('success');
						    }
						});
				},
				fail: res => {
					console.log(res)
					console.log('cccccc')
				}
			});
		});
	},
	
}

export default tui